package org.cupk2.main.cecurity.service;

import org.cupk2.base.domain.CupkUserContext;
import org.cupk2.base.event.face.Cupk2Events;
import org.cupk2.base.event.enums.F2EActionT;
import org.cupk2.base.event.enums.F2EObjectT;
import org.cupk2.main.cecurity.service.domain.OnlineUser;
import org.cupk2.service.inter.CupkUserServiceInter;
import org.cupk2.tools.caches.CupkCacheKeys;
import org.cupk2.tools.caches.CupkCaches;
import org.cupk2.tools.structure.ResourceInfo;

import java.util.Date;

/**
 * 管理用户的在线状态（用于执行登录用户注销，登录，信息缓存）
 */
public class CupkUserOnlines {

    /**
     * 用户登录
     *
     * @param userContext
     */
    public static void login(CupkUserContext userContext) {
        CupkCaches.getInstance().putCacheData(userContext.getLoginname(), userContext, CupkCacheKeys.LOGIN_USER);
        Cupk2Events.emit(F2EObjectT.USER, userContext.getLoginname(), F2EActionT.LOGIN, userContext);
    }

    /**
     * 用戶登出
     *
     * @param user
     */
    public static void logout(CupkUserContext user) {
        CupkCaches.getInstance().removeCacheData(user.getLoginname(), CupkCacheKeys.LOGIN_USER);
        Cupk2Events.emit(F2EObjectT.USER, user.getLoginname(), F2EActionT.LOGOUT, user);
    }

    /**
     * JwtAuthenticationTokenFilter中使用获取缓存用户信息(记录在线状态)
     *
     * @param loginname
     * @param loginid
     * @param cupkUserService
     * @return
     */
    public static CupkUserContext getUser(String loginname, String loginid, String ip, CupkUserServiceInter cupkUserService) {
        CupkUserContext userContext = CupkCaches.getInstance().getCacheData(loginname, CupkCacheKeys.LOGIN_USER);
        if (userContext == null) {
            userContext = cupkUserService.getUserByLoginName(loginname);
            userContext.setLoginid(loginid);
            CupkCaches.getInstance().putCacheData(loginname, userContext, CupkCacheKeys.LOGIN_USER);
        }
        OnlineUser ouser = CupkCaches.getInstance().getCacheData(loginname + ip, CupkCacheKeys.ONLINE_USER);
        if (ouser == null) {
            CupkCaches.getInstance().putCacheData(loginname + ip, new OnlineUser(ip, userContext.getName(), loginname, loginid), CupkCacheKeys.ONLINE_USER);
        } else {

            ouser.setEndTime((new Date()).getTime());

        }
        return userContext;
    }

    /**
     * 获得当前在线用户
     *
     * @return
     */
    public static ResourceInfo getOnlineNum() {
        int onlineNum = CupkCaches.getInstance().getCacheSize(CupkCacheKeys.ONLINE_USER, true);
        return new ResourceInfo("在线用户", onlineNum);
    }
}
